/**
 * Created by xinhuang on 15/2/13.
 */
;
(function () {
  'use strict';
  angular.module('sasApp.services', [
    'services.login',
    'services.omdisplay',
    'services.faultLocation',
    'services.usermanager',
    'services.timeDataDis',
    'services.sysServiceData',
    'services.resourcesWatchData',
    'services.resource',
    'services.customActivity',
    'services.analysisSysOM',
    'services.dataQualityMng',  //数据管理
    //'services.alarmStatisticsAnalysis',
    'services.workOrderData',
    'services.alarmDataAnalysis',//告警数据分析
    'services.userBehaviorAnalysis', //用户行为指标分析
    'services.sysBusinessStatistic'
  ])
    .service('CoreLoading', CoreLoading)
    .factory('CoreService', CoreService)
    .factory('CoreServer', CoreServer)
    .factory('COREDATA', COREDATA)
    .factory('PublicFn', PublicFn)
    .factory('SystemModulesService',SystemModulesService)
    .factory('sasInterceptor',sasInterceptor);
  /**
   * [CoreLoading 页面等待效果]
   */
  function CoreLoading($rootScope) {
    this._loading = $rootScope._loading;
    this.setState = function (isShow) {
      this._loading.show = isShow;
    };
  }

  /**
   * [COREDATA 核心数据]
   */
  function COREDATA() {
    return {
      TIMETYPES: [
        {
          timeTypeCode: '1',
          timeTypeName: '日'
        }, {
          timeTypeCode: '3',
          timeTypeName: '月'
        }, {
          timeTypeCode: '4',
          timeTypeName: '季'
        }, {
          timeTypeCode: '5',
          timeTypeName: '年'
        }
      ],
      QUARTERS: [
        {
          quarterCode: '1',
          quarterName: '第一季度'
        }, {
          quarterCode: '2',
          quarterName: '第二季度'
        }, {
          quarterCode: '3',
          quarterName: '第三季度'
        }, {
          quarterCode: '4',
          quarterName: '第四季度'
        }
      ],
      ERRORINFO: {
        startTime: ['开始时间不应大于结束时间', '开始时间不应大于当前时间'],
        endTime: ['结束时间不应小于开始时间', '结束时间不应大于当前时间']
      },
      SYSTEM: [],
      PROVINCES: [],
      ROLES: [],
      FORMPREFIX: '',
      SOCKETIP: '192.168.0.65:9092',
      USERINFO: {
        REALNAME: ''
      }
    };
  }

  function CoreService($mdDialog,$state){
    var _loading = {show:false};
    return {
      dateFormat: dateFormat,
      dialog: alertDialog,
      navgit: navgit,
      sort: sort,
      _loading:_loading
    };
    /**
     * [format 日期格式化]
     */
    function dateFormat(time, formatType) {
      var t = new Date(time);
      var tf = function (i) {
        return (i < 10 ? '0' : '') + i;
      };
      return formatType.replace(/yyyy|MM|dd|hh|mm|ss/g, function (a) {
        switch (a) {
          case 'yyyy':
            return tf(t.getFullYear());
          case 'MM':
            return tf(t.getMonth() + 1);
          case 'mm':
            return tf(t.getMinutes());
          case 'dd':
            return tf(t.getDate());
          case 'hh':
            return tf(t.getHours());
          case 'ss':
            return tf(t.getSeconds());
        }
      });
    }

    /**
     * [alertDialog 提示框]
     * @param  {[string]} content [提示内容]  或 [错误状态码]
     * @param  {[string]} title [提示标题]
     */
    function alertDialog(content, title) {
      var contents = {
        '10000': '当前条件无数据',
        '10001': '操作失败',
        '10002': '验证重复',
        '10003': '系统繁忙',
        '10004': '用户名或密码错误',
        '10005': '密码验证失败',
        '10006': '用户不存在',
        '10007': '流水号与条件不符合',
        '10009': '登陆超时，请重新登陆'
      };
      if (isNaN(Number(content))) {
        $mdDialog.show(
          $mdDialog.alert()
            .clickOutsideToClose(true)
            .title(title || '提示')
            .content(content)
            .ok('确定')
        );
      } else {
        $mdDialog.show(
          $mdDialog.alert()
            .clickOutsideToClose(true)
            .title(title || '提示')
            .content(contents[content])
            .ok('确定')
        );
      }
    }

    /**
     * [修复导航栏刷新问题]
     * @return {[Number]} [selectedIndex]
     */
    function navgit(tabs) {
      var o,p;
      for (p in tabs) {
        if ($state.current.url === tabs[p]) {
          o = Number(p);
        }
      }
      return o;
    }

    function sort(series, compareKey) {
      var arr = [];
      if (is.array(series)) {
        arr = series;
      } else {
        for (var o in series) {
          arr.push(series[o]);
        }
      }
      arr.sort(function (x, y) {
        return Number(x[compareKey]) - Number(y[compareKey]);
      });
      return arr;
    }
  }

  function CoreServer(Restangular) {
    return {
      getProvince: getProvince,
      getSystem: getSystem,
      getBank: getBank,
      getSysBusiness: getSysBusiness,
      getBusiness: getBusiness,
      getServerTime: getServerTime,
      getRoles: getRoles,
      logOut: logOut,
    };
    //省份
    function getProvince() {
      return Restangular.one('sas/common/provinceQuery').get();
    }
    //系统
    function getSystem() {
      return Restangular.one('sas/common/sysQuery').get();
    }
    //银行
    function getBank() {
      return Restangular.one('sas/common/bankQuery').get();
    }
    //业务
    function getSysBusiness(param, callback) {
      return Restangular.all('sas/common/businessQuery').post(param).then(callback);
    }
    //业务线
    function getBusiness() {
      return Restangular.one('sas/common/businessLineQuery').get();
    }
    //获取服务器时间
    function getServerTime() {
      return Restangular.one('sas/common/getServerTime').get();
    }
    //获取角色
    function getRoles() {
      return Restangular.one('sas/sysMng/role/roleQuery').get();
    }
    function logOut(callback){
      return Restangular.one('sas/common/exit').get().then(callback);
    }
  }
  function PublicFn(){
    return {
      fmtDateTitle: fmtDateTitle
    };
    /**
     *@fmtDateTitle {object}    格式化时间标题,根据选择不同的时间类型,给予不同的时间标题:
     *如开始时间为:2014-01-01,结束时间为:2015-01-01,则获取的标题为'2014年01月01号 至 2015年01月01号'
     *当开始时间和结束时间相同时,只显示开始时间
     * @send  {object} 里面包含send.startTime,send.endTime
     * @prototypeName  {string}  send对象里面的属性名.用来确定账期的字段名
     * @return {string} 返回的字符串.如:2014年01月01号 至 2015年01月01号
     */
    function fmtDateTitle(send,prototypeName){
      var timeTitle = '';
      var timeType = send[prototypeName];
      if(!timeType){
        timeType = '1';
      }
      var booleanTime = send.startTime === send.endTime;
      //2014-01-01
      var startYear = send.startTime.substring(0, 4)+'年';
      var endYear = send.endTime.substring(0, 4)+'年';
      var startMonth = send.startTime.substring(5, 7)+'月';
      var endMonth = send.endTime.substring(5, 7)+'月';
      var startDay = send.startTime.substring(8, 10)+'日';
      var endDay = send.endTime.substring(8, 10)+'日';
      var startHour = send.startTime.substring(11,13)+'时';
      var endHour = send.endTime.substring(11,13)+'时';
      switch(timeType){
        case '5':
          timeTitle  = booleanTime ? startYear : startYear+' 至 '+ endYear;
          break;
        case '4':
          var startQuarterName = getQuarterName(send.startQuarter);
          var endQuarterName = getQuarterName(send.endQuarter);
          if(booleanTime){
            timeTitle = startYear+startQuarterName;
          }else {
            timeTitle = startYear + startQuarterName +' 至 ' + endYear + endQuarterName;
          }
          break;
        case '3':
          timeTitle = booleanTime ? startYear + startMonth : startYear + startMonth + ' 至 ' + endYear + endMonth;
          break;
        case '0' :
          if(booleanTime){
            timeTitle = startYear + startMonth + startDay + startHour;
          }else {
            timeTitle = startYear + startMonth + startDay + startHour +' 至 ' + endYear + endMonth + endDay + endHour;
          }
          break;
        default:
          if(booleanTime){
            timeTitle = startYear + startMonth + startDay;
          }else {
            timeTitle =  startYear + startMonth + startDay +' 至 ' + endYear + endMonth + endDay;
          }
          break;
      }
      return timeTitle;
    }
    //根据不同的季度code,显示不同的季度名称，拼接标题季度使用的方法
    function getQuarterName(data){
      var quarterName = '';
      switch (data) {
        case '1':
          quarterName = '第一季度';
          break;
        case '2':
          quarterName = '第二季度';
          break;
        case '3':
          quarterName = '第三季度';
          break;
        case '4':
          quarterName = '第四季度';
          break;
      }
      return quarterName;
    }
  }
  function SystemModulesService(Restangular){
    var obj = {
      _modules: {},
      getSystemModules: getSystemModules
    };

    return obj;

    function getSystemModules(params,callback){
      return Restangular.one(params+'/allSystemModules').get().then(function(res){
        obj._modules = res.data;
        callback(res);
      });
    }
  }
  function sasInterceptor($q){
    return {
      'responseError': function(response) {
        console.log(response);
        if(response.status == 302){
          window.location.href= response.data;
        }
        return $q.reject(response);
      }
    }
  }
})();
